<?php

namespace app\backend\controller;

use app\common\model\Feed;
use think\Request;

class Article extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = model("feed")->order("id DESC")->paginate(30);
        $this->assign("list", $list);
        return $this->fetch();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return $this->fetch();
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $title = $request->post("title", "");
        $content = $request->post("content", "");
        if ($title == "" || $content == "") {
            $this->error("请输入完整的内容");
        }
        if (!Feed::create([
            'title' => $title,
            'content' => $content,
            'uid' => 1
        ])) {
            $this->error("文章添加失败 请稍后再试");
        };

        $this->success("文章保存成功");
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $article = Feed::get($id);
        $this->assign("article", $article);
        return $this->fetch();
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     * @throws \think\exception\DbException
     */
    public function update(Request $request, $id)
    {
        $title = $request->post("title", "");
        $content = $request->post("content", "");
        if ($title == "" || $content == "") {
            $this->error("请输入完整的内容");
        }
        $article = Feed::get($id);
        if (!$article) {
            $this->error("文章不存在");
        }
        if (!$article->where(['id'=>$id])->update([
            'title' => $title,
            'content' => $content
        ])) {
            $this->error("文章修改失败 请稍后再试");
        };
        $this->success("文章修改成功");
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @throws \think\exception\DbException
     */
    public function delete($id)
    {
        $article = Feed::get($id);
        if (!$article) {
            $this->error("文章不存在");
        }
        if (!$article->delete()) {
            $this->error("文章删除失败");
        }
        $this->success("文章删除成功");
    }
}
